﻿using DevExpress.XtraEditors;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Equipment.Select;
using MesProjectWinform.Public;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.DeviceLedger
{
    /// <summary>
    /// 设备台账添加页面
    /// </summary>
    public partial class DeviceLedgerAddForm : DevExpress.XtraEditors.XtraForm
    {
        public DeviceLedgerAddForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 点击保存按钮，添加设备台账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AddDeviceLedgerButton1_Click(object sender, EventArgs e)
        {
            // 禁用保存按钮，防止重复提交
            simpleButton1.Enabled = false;

            try
            {
                // 1. 数据验证
                // 验证设备名称不能为空
                if (string.IsNullOrWhiteSpace(DeviceLedgerName.Text))
                {
                    XtraMessageBox.Show("设备名称不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    DeviceLedgerName.Focus();
                    return;
                }

                // 验证设备类型必须选择
                if (DeviceTypeId.EditValue == null)
                {
                    XtraMessageBox.Show("请选择设备类型", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    DeviceTypeId.Focus();
                    return;
                }

                // 验证设备数量为有效数字
                if (!int.TryParse(DeviceNum.Text, out int deviceNum))
                {
                    XtraMessageBox.Show("设备数量必须是有效数字", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    DeviceNum.Focus();
                    return;
                }

                // 2. 创建设备台账对象并赋值
                DeviceLedgerOutput deviceLedgerOutput = new DeviceLedgerOutput();

                // 基本信息赋值
                deviceLedgerOutput.DeviceLedgerName = DeviceLedgerName.Text; // 设备名称
                deviceLedgerOutput.DeviceBrand = DeviceBrand.Text;           // 设备品牌
                deviceLedgerOutput.DeviceType = DeviceType.Text;             // 设备型号
                deviceLedgerOutput.DeviceSpeciFication = DeviceSpeciFication.Text; // 设备规格
                deviceLedgerOutput.DeviceNum = deviceNum;                    // 设备数量

                // 位置和责任信息赋值
                deviceLedgerOutput.Devicelocation = Devicelocation.Text;         // 位置
                deviceLedgerOutput.DeviceuseDepartments = DeviceuseDepartments.Text; // 使用部门
                deviceLedgerOutput.DeviceHead = DeviceHead.Text;                 // 负责人
                deviceLedgerOutput.DeviceRemark = DeviceRemark.Text;             // 备注

                // 处理生产日期字段，若未选择则默认为当前时间
                if (DeviceBeginTime.EditValue != null)
                {
                    deviceLedgerOutput.DeviceBeginTime = DeviceBeginTime.DateTime;
                }
                else
                {
                    deviceLedgerOutput.DeviceBeginTime = DateTime.Now;
                }

                // 处理入场时间字段，若未选择则默认为当前时间
                if (DeviceEnterTime.EditValue != null)
                {
                    deviceLedgerOutput.DeviceEnterTime = DeviceEnterTime.DateTime;
                }
                else
                {
                    deviceLedgerOutput.DeviceEnterTime = DateTime.Now;
                }

                // 3. 处理下拉框字段
                // 设备类型ID和名称
                if (DeviceTypeId.EditValue is DeviceTypeOuput deviceType)
                {
                    deviceLedgerOutput.DeviceTypeId = deviceType.Id;
                    deviceLedgerOutput.DeviceTypeName = deviceType.DeviceTypeName;
                }
                else if (DeviceTypeId.EditValue != null)
                {
                    try
                    {
                        deviceLedgerOutput.DeviceTypeId = Convert.ToInt64(DeviceTypeId.EditValue);
                    }
                    catch
                    {
                        XtraMessageBox.Show("设备类型数据格式无效", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        DeviceTypeId.Focus();
                        return;
                    }
                }


                // 供应商ID和名称
                if (SupplierId.EditValue is SupplierOutput supplier)
                {
                    deviceLedgerOutput.SupplierId = supplier.Id;
                    deviceLedgerOutput.SupplierName = supplier.SupplierName;
                }
                else if (SupplierId.EditValue != null)
                {
                    try
                    {
                        deviceLedgerOutput.SupplierId = Convert.ToInt64(SupplierId.EditValue);
                    }
                    catch
                    {
                        XtraMessageBox.Show("供应商数据格式无效", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        SupplierId.Focus();
                        return;
                    }
                }

                // 车间ID和名称
                if (WorkShopId.EditValue is WorkShopOutput workShop)
                {
                    deviceLedgerOutput.WorkShopId = workShop.Id;
                    deviceLedgerOutput.WorkShopName = workShop.WorkShopName;
                }
                else if (WorkShopId.EditValue != null)
                {
                    try
                    {
                        deviceLedgerOutput.WorkShopId = Convert.ToInt64(WorkShopId.EditValue);
                    }
                    catch
                    {
                        XtraMessageBox.Show("车间数据格式无效", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        WorkShopId.Focus();
                        return;
                    }
                }

                // 4. 添加审计字段（创建时间、更新时间）
                deviceLedgerOutput.CreatedTime = DateTime.Now;
                deviceLedgerOutput.UpdatedTime = DateTime.Now;

                // 5. 显示等待光标，准备调用API
                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    // 创建HttpClient实例
                    using (var client = new HttpClient())
                    {
                        // 设置超时时间为30秒
                        client.Timeout = TimeSpan.FromSeconds(30);

                        // 将对象序列化为JSON字符串
                        var json = JsonConvert.SerializeObject(deviceLedgerOutput);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");

                        // 发送POST请求到API
                        var response = await client.PostAsync("http://localhost:5229/api/DeviceLedger/AddDeviceLedger", content);

                        // 处理响应
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            var responseContent = await response.Content.ReadAsStringAsync();
                            // 反序列化为ApiResult<long>对象
                            var result = JsonConvert.DeserializeObject<ApiResult<long>>(responseContent);

                            // 判断返回结果
                            if (result != null && result.Code == ApiEnums.Success)
                            {
                                // 添加成功，提示并关闭窗口
                                XtraMessageBox.Show("设备台账添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                this.DialogResult = DialogResult.OK;
                                this.Close();
                            }
                            else
                            {
                                // 添加失败，显示错误信息
                                string errorMessage = result != null ? result.Message : "未知错误";
                                XtraMessageBox.Show($"添加失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show($"请求失败，状态码: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                catch (HttpRequestException ex)
                {
                    XtraMessageBox.Show($"网络请求错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (TaskCanceledException)
                {
                    XtraMessageBox.Show("请求超时，请检查网络连接或服务器状态", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (JsonException ex)
                {
                    XtraMessageBox.Show($"JSON数据处理错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (FormatException ex)
                {
                    XtraMessageBox.Show($"数据格式错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"保存时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                // 恢复保存按钮状态
                simpleButton1.Enabled = true;
            }
        }


        /// <summary>
        /// 加载下拉事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DeviceLedgerAddForm_Load(object sender, EventArgs e)
        {
            await LoadSelect();
        }

        /// <summary>
        /// 加载下拉框
        /// </summary>
        /// <returns></returns>
        private  async Task LoadSelect()
        {
            using (var client = new HttpClient())
            {
                #region 设备类型
                var response = await client.GetStringAsync("http://localhost:5229/api/DeviceLedger/GetDeviceTypeValue");
                var result = JsonConvert.DeserializeObject<ApiResult<List<DeviceTypeOuput>>>(response);
                if (result != null && result.Data != null)
                {
                    //设置下拉列表的数据源
                    DeviceTypeId.Properties.DataSource = result.Data;
                    //设置显示的字段
                    DeviceTypeId.Properties.DisplayMember = "DeviceTypeName";
                    DeviceTypeId.Properties.ValueMember = "Id";


                    //设置下拉列表的列
                    DeviceTypeId.Properties.Columns.Clear();
                    DeviceTypeId.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("DeviceTypeName", "设备类型名称"));

                    DeviceTypeId.Properties.NullText = "请选择设备类型";
                }
                #endregion

                #region 供应商

                List<SupplierOutput> supplierOutputs = new List<SupplierOutput>()
                {
                    new SupplierOutput()
                    {
                        Id = 1,
                        SupplierName = "联创电子"
                    },
                    new SupplierOutput()
                    {
                        Id = 2,
                        SupplierName = "宇瞳光学"
                    },
                    new SupplierOutput()
                    {
                        Id = 3,
                        SupplierName = "银禧科技"
                    },
                    new SupplierOutput()
                    {
                        Id = 4,
                        SupplierName = "宝武镁业"
                    },
                    new SupplierOutput()
                    {
                        Id = 5,
                        SupplierName = "博通集成"
                    },
                    new SupplierOutput()
                    {
                        Id = 6,
                        SupplierName = "宝武镁业"
                    },
                    new SupplierOutput()
                    {
                        Id = 7,
                        SupplierName = "海能达"
                    },
                    new SupplierOutput()
                    {
                        Id = 8,
                        SupplierName = "显盈科技"
                    },
                    new SupplierOutput()
                   {
                        Id = 9,
                        SupplierName = "京山轻机"
                    },
                };

                if (supplierOutputs != null)
                {
                    //设备数据源
                    SupplierId.Properties.DataSource = supplierOutputs;
                    //设置显示的字段
                    SupplierId.Properties.DisplayMember = "SupplierName";

                    //设置下拉列表的列
                    SupplierId.Properties.Columns.Clear();
                    SupplierId.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("SupplierName", "供应商名称"));

                    SupplierId.Properties.NullText = "请选择供应商";
                }
                #endregion

                #region 车间
                List<WorkShopOutput> workShopOutputs = new List<WorkShopOutput>()
                {
                    new WorkShopOutput()
                    {
                        Id = 1,
                        WorkShopName = "零部件加工车间"
                    },
                    new WorkShopOutput()
                    {
                        Id = 2,
                        WorkShopName = "模块组装车间"
                    },
                    new WorkShopOutput()
                    {
                        Id = 3,
                        WorkShopName = "整机总装车间"
                    },
                    new WorkShopOutput()
                    {
                        Id = 4,
                        WorkShopName = " 功能测试车间"
                    },
                    new WorkShopOutput()
                    {
                        Id = 5,
                        WorkShopName = " 物料仓储与配送车间"
                    },
                    new WorkShopOutput()
                    {
                        Id = 6,
                        WorkShopName = " 包装与物流车间"
                    },
                     new WorkShopOutput()
                    {
                        Id = 7,
                        WorkShopName = " 返工维修车间"
                    },
                };

                //设备数据源
                WorkShopId.Properties.DataSource = workShopOutputs;
                //设置显示的字段
                WorkShopId.Properties.DisplayMember = "WorkShopName";

                //设置下拉列表的列
                WorkShopId.Properties.Columns.Clear();
                WorkShopId.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("WorkShopName", "车间名称"));

                WorkShopId.Properties.NullText = "请选择车间";
                #endregion 

            }
        }

        
    }
}